import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaLocaleProvider,WeaNewScroll, WeaBrowser } from 'ecCom';
import { Button, Spin, Tooltip } from 'antd';
import RightTab from './rightTab/index';
import { observable, action, toJS } from 'mobx';
import * as myWorkPlanApi from '../../../apis/myWorkPlan';
import moment from 'moment';
import { setWorkplanCalendarI18n } from'../../../lib/wdCalendar_lang_wev8';

const i18n=window.workplanCalendarI18n;
const { getLocaleLabelByCode } = WeaLocaleProvider;
const ButtonGroup = Button.Group;
const getLabel = WeaLocaleProvider.getLabel;
let LASTSTATUS = false;
let thisSign=''
let nextSign='1'
@inject('myWorkPlanStore')
@observer
class RightContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeType: '',
      selected: '-9900',
      selectedUser: '',
      date: new Date(),
      url:'',
      isIE: !!window.ActiveXObject || "ActiveXObject" in window || navigator.userAgent.indexOf('Firefox') >= 0,
    }
  }
  componentWillMount(){

  }
  componentDidMount() {
    let { isAllWorkPlan = false, query = false} = this.props;
    let isShare = isAllWorkPlan ? 2 : 1;
    let { calendarParams, DATA_FEED_URL, status, onlyChangeSelectedUser,dialogHeight,setParams} = this.props.myWorkPlanStore
    status = toJS(status);
    let { timeType, date, defBgTime, defEdTime, defBgTimeStr, defEdTimestr, selectedUser, zone_offset,titleFold, layoutType} = status;
    if(query && selectedUser != query.selectedUser)onlyChangeSelectedUser(query.selectedUser);
    timeType = timeType == '' ? 'week' : timeType;
    //获取客户端时区
    const clientTimeZone = new Date().getTimezoneOffset()/60;
    let millTime = new Date().getTime();
    setParams({isWorkplanView: true}); // 标记日程一览表页面
    if(zone_offset !== (-clientTimeZone)){
      millTime = millTime + (clientTimeZone+zone_offset)*60*60*1000;
    }
    let op = {
      view: timeType,//指定显示的视图（周，月，日）
      theme: '#a32929',//指定默认模板，比如拖拽新建日程时日程的颜色
      showday: new Date(millTime),//指定显示的日期，在视图中显示的日， 周，月为当前指定日期所在的日，周，月。
      DeleteCmdhandler: () => { },//删除日程的回调函数
      EditCmdhandler: (e) => { this.edit(e) },//编辑日程的回调函数
      ViewCmdhandler: (e) => { this.view(e) },    //查看日程的回调函数
      autoload: true,
      defBgTime: defBgTime,
      defEdTime: defEdTime,
      defBgTimeStr: defBgTimeStr,
      defEdTimestr: defEdTimestr,
      selectedUser: '',//指定当前选定的人员
      isShare: isShare,//（isShare：1 显示“所有日程”，其他：显示“我的日程”
      workPlanType: '',//日程类型默认为全部，全部传空
      url: DATA_FEED_URL + "?method=list&selectUser=",  //视图中日程项数据请求url
      quickAddHandler: true,
      doGetData: () => { this.getData(false) },
      newData: '',
      canSave: false,
      weekstartday: 0
    };
    let _MH = document.documentElement.clientHeight;//浏览器高度
    let _dvH = _MH - 144 + 8 - 67 + 30 + 8;//144为上面的height,67为ecology系统菜单
    if(window.location.href.indexOf("/spa/workplan/static/index")>-1||window.location.href.indexOf("/#/")>-1){
        _dvH = _MH -144 + 8 + 30 + 8;
    }
    if(layoutType === "2" && !(window.location.href.indexOf("/spa/workplan/static/index")>-1||window.location.href.indexOf("/#/")>-1)){
      _dvH = _dvH - 45 - 10;
    }
    op.height = _dvH;
    if(query && query.hrmWorkplanHeight){//人力卡片里面调用日程的时候会传高度
      op.height = query.hrmWorkplanHeight;
    }
    if(dialogHeight>0){
      op.height =dialogHeight;
    }
    jQuery("#gridcontainer").bcalendar(op);
    this.getLanguage();
  }
  shouldComponentUpdate(nextProps,nextState) {

  }
  componentWillReceiveProps(nextProps) {
    if(this.props.time4RightCon!=nextProps.time4RightCon){
      thisSign=this.props.time4RightCon
      nextSign=nextProps.time4RightCon
      this.getData(true)
   }
     
    let { isAllWorkPlan = false, query = false} = this.props;
    let { status, updateCalender, onlyChangeSelectedUser,changetableScrollltop} = nextProps.myWorkPlanStore;
    status = toJS(status);
    let { update, isInit, workPlanShow} = status;
    if(query && query.selectedUser != status.selectedUser)onlyChangeSelectedUser(query.selectedUser)
    let view = '';
    let selected = '-9900';
    let selectedUser = '';
    let date = new Date();
    if (status.timeType != this.state.timeType) {
      view = status.timeType;
      selected = status.selected;
      selectedUser = status.selectedUser;
      date = status.date;
      (isInit == 'true') && this.setState({ url: '' }, this.changeInit('false'));
      (isInit == 'false') && workPlanShow == 'calender' && status.timeType && this.setState({ timeType: view }, this.doRefreshCalender('', selected, selectedUser, false, date, true))
    }
    if (status.selected != this.state.selected) {
      view = status.timeType;
      selected = status.selected;
      selectedUser = status.selectedUser;
      date = status.date;
      workPlanShow == 'calender' && status.timeType && this.setState({ selected: selected }, this.doRefreshCalender('', selected, selectedUser, false, date, true))
    }
    if (status.selectedUser != this.state.selectedUser) {
      view = status.timeType;
      selected = status.selected;
      selectedUser = status.selectedUser;
      date = status.date;
      workPlanShow == 'calender' && status.timeType && this.setState({ selectedUser: selectedUser }, this.doRefreshCalender('', selected, selectedUser, false, date, true))
    }
    if (this.changeDateFormat(status.date) != this.changeDateFormat(this.state.date)) {
      view = status.timeType;
      selected = status.selected;
      selectedUser = status.selectedUser;
      date = status.date;
      workPlanShow == 'calender' && status.timeType && this.setState({ date: date }, this.doRefreshCalender('', selected, selectedUser, false, date, true))
    }
    if (update) {//手动刷新 
      selected = status.selected;
      selectedUser = status.selectedUser;
      date = status.date;
      workPlanShow == 'calender' && status.timeType && this.doRefreshCalender('', selected, selectedUser, false, date, true)
    }
    // 解决滚动条宽度占位问题 start
    // changetableScrollltop(false); 
    // end
  }
  componentDidUpdate() {
    const {changetableScrolllright,status} = this.props.myWorkPlanStore;
    const {titleFold,timeType, isSpinning} = status
    this.setLeftTrheight();
    // this.soveScrollbarWidth() ? changetableScrolllright(true) : changetableScrolllright(false);
    timeType == 'week' && this.weeksScrollWidth();
    if ( LASTSTATUS != isSpinning ) {
      this.setScrollLeft();
    }
    LASTSTATUS = isSpinning;
  }

  componentWillUnmount() {
    const {setParams} = this.props.myWorkPlanStore;
    setParams({isWorkplanView: false}); // 标记日程一览表页面
  }

  getLanguage = () => {
    getLocaleLabelByCode('workplan').then(res => {
      typeof setWorkplanCalendarI18n === 'function' && setWorkplanCalendarI18n(() => {
        typeof jQuery("#gridcontainer").reloadLanguage === 'function' && jQuery("#gridcontainer").reloadLanguage();
      });
    });
  }

  setScrollLeft = () => {
    const {status} = this.props.myWorkPlanStore;
    if (status.timeType === 'month' && this.refs.hearderTimeItem && this.refs.rightTable) { // 解决上次滚到中部后切换数据显示样式问题
      this.refs.hearderTimeItem.scrollLeft = 0;
      this.refs.rightTable.scrollLeft = 0;
    }
  }

  setLeftTrheight = () => {
    const {amAndPm,timeType} = this.props.myWorkPlanStore.status;
    let trHeight = [];
    let trArr = jQuery("#display-workplanItem-container tbody tr");
    let leftTrHeight = jQuery('#left-content-tr tr');
    if(trArr.length > 0) {
      for(let item in trArr) {
        if(item === 'length'){
          break;
        }
        let h = trArr[item].getBoundingClientRect().height;
        let height = item == '0' ? h+1 : h;
        trHeight.push(height+'px');
      }
    }
    if(leftTrHeight.length > 0) {
      let loc = 0;
      for(let item in leftTrHeight) {
        if(item === 'length'){
          break;
        }
        !amAndPm ? jQuery('#left-content-tr tr').find('td').eq(loc).css({'height':trHeight[loc],})
          : jQuery('#left-content-tr').find('tr').eq(loc).css({'height':trHeight[loc],});
        loc++;
      }
    }
  }

  weeksScrollWidth = () => {
    const {setParams} = this.props.myWorkPlanStore;
    if(this.refs.rightTable && this.refs.rightTop && ( this.refs.rightTable.offsetHeight>this.refs.rightTop.offsetHeight)) {
      setParams({weekScrolllwidth: true});
    }else{
      setParams({weekScrolllwidth: false});
    }
  }

  render() {
    let amMax = [];
    let pmMax = [];
    let { status, getRightMenu, onRightMenuClick, changeTimeType, updateCalender,tableScrolllright,isGetCalendarData,weekScrolllwidth } = this.props.myWorkPlanStore;
    status = toJS(status)
    let { loading, timeType, userList, date, dateMoment, memberids, dayOfWeek, spinning,isSpinning, workPlanShow,amAndPm,useMap,useMap_pm,dataRule } = status;
    let HH = 25;
    let browserParam = {
      hasAddBtn: false,
      hasAdvanceSerach: true,
      idSeparator: ",",
      isAutoComplete: 1,
      isDetail: 0,
      isMultCheckbox: false,
      isSingle: true,
      linkUrl: "/hrm/resource/HrmResource.jsp?id=",
      pageSize: 10,
      quickSearchName: "",
      title: `${getLabel(179,'人力资源')}`,
      type: "1",
      viewAttr: 2,
    }
    let { blockNum, tableTitle, tableHeaders } = this.getTableHeaderInfo(timeType, dateMoment);
    let tableWidth = jQuery(".right-top").width();
    let one_width=amAndPm?130:107;
    let seven_width=this.state.isIE ? 35 : (amAndPm?10:8);
    let thStyle = blockNum == 1 ? { width: (tableWidth - one_width), textAlign: 'center' } : blockNum == 7 ? { width: (tableWidth-seven_width ) / 7 - 2, textAlign: 'center' } : { width: '130px', textAlign: 'center' };
    let tableContent = (
      (memberids && memberids.length > 0) &&
      memberids.map((room, index) => {
        let replaceDatas = [];
        let amp=['am','pm'];

        replaceDatas.push(room);
        let tdList = this.createTdList(room, blockNum, useMap, dayOfWeek, thStyle);
        let tdList_pm =[];
        if(amAndPm){
          tdList_pm=this.createTdList(room, blockNum, useMap_pm, dayOfWeek, thStyle);
        }
        const getMax = (tdList,tdList_pm) => {
          let ammax = 0; 
          let pmmax = 0; 
          if(tdList) {
            if(!(tdList instanceof Array)) { // 日模式下tdList不是数组，转化成数组
              let arr = [];
              arr.push(tdList);
              tdList = arr;
            }
            tdList instanceof Array && tdList.map(res => {
              ammax = res.props.children.length>ammax ? res.props.children.length : ammax;
            })
            amMax.push(ammax);
          }
          if(tdList_pm) {
            if(!(tdList_pm instanceof Array)) {
              let arr = [];
              arr.push(tdList_pm);
              tdList_pm = arr;
            }
            tdList_pm instanceof Array && tdList_pm.map(res => {
              pmmax = res.props.children.length>pmmax ? res.props.children.length : pmmax;
            })
            pmMax.push(pmmax);
          }
        }
        getMax(tdList,tdList_pm);

        return (
          amAndPm ? 
          (amp.map((key, index)=>{
              return (
                  key==='am' ?
                  <tr className={index == 0 ? "no-border-top" : ""} >
                      {tdList}
                  </tr>
                  :
                  <tr className={index == 0 ? "no-border-top" : ""}>
                      {tdList_pm}
                  </tr>
              );
          }))
          :
          <tr className={index == 0 ? "no-border-top" : ""}>
            {tdList}
          </tr>
        );
      })
    );
    
    let leftContent = (
      (memberids && memberids.length > 0) &&
      memberids.map((room, index) => {
        let replaceDatas = [];
        let amp=['am','pm'];
        
          replaceDatas.push(room);
          return (
            amAndPm ? 
            (amp.map((key, i)=>{
                return (
                    key==='am' ?
                    <tr className={i == 0 ? "no-border-top" : ""} style={{height: amMax[index]*HH+1}}>
                        <td style={{ backgroundColor: '#f5f7fa', borderLeft: 'none',verticalAlign:"middle",textAlign: "center" }} rowSpan={2}>
                          <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@u0gmls@${room.id}`} {...browserParam} viewAttr={1} replaceDatas={replaceDatas} inputStyle={{ width: '100px' }} />
                        </td>
                        <td style={{verticalAlign:"middle",textAlign: "center",width: 45,borderRight:'1px solid #E2E2E2'}}>{i18n.langId==='8'?'AM':getLabel(16689,'上午')}</td>
                    </tr>
                    :
                    <tr className={i == 0 ? "no-border-top" : ""} style={{height: pmMax[index]*HH+1}}>
                        <td style={{verticalAlign:"middle",textAlign: "center",width: 45,borderRight:'1px solid #E2E2E2'}}>{i18n.langId==='8'?'PM':getLabel(16690,'下午')}</td>
                    </tr>
                );
            }))
            :
            <tr className={index == 0 ? "no-border-top" : ""}>
              <td style={{ backgroundColor: '#f5f7fa', borderLeft: 'none',verticalAlign:"middle",textAlign: "center", 
                  height: amMax[index]*HH+1}}>
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@750ahd@${room.id}`} {...browserParam} viewAttr={1} replaceDatas={replaceDatas} inputStyle={{ width: '145px' }} />
              </td>
            </tr>
          );
        })
      );
    let thHeaderStyle = timeType==='week'&&weekScrolllwidth ? { width: (tableWidth-seven_width ) / 7 - 3,textAlign: 'center', height: '44px', lineHeight: '44px',} : { ...thStyle, height: '44px', lineHeight: '44px',}
    let {style=false} = this.props;
    let normalStyle = { /*paddingLeft: '221px',*/ width: '100%', height: '100%' };
    if(workPlanShow==='list'){
      normalStyle = {width: '100%', height: '100%' }
    } 
    let hrmStyle = {}
    if(style){
      hrmStyle = {...normalStyle, ...style}
    }else{
      hrmStyle = normalStyle
    }

    if (this.props.hidesidebar === 'true' || this.props.hidesidebar) { // 根据url中的参数判断是否显示左侧边栏
      hrmStyle = {...hrmStyle, paddingLeft: '0px'};
    }
    let dataRuleStr=dataRule==1?getLabel(882,'创建人'):getLabel(15525,'接收人');
    return (
      <div className="myWorkplan-right" id='myWorkplanright2' style={hrmStyle}>
        <RightTab ecId={`${this && this.props && this.props.ecId || ''}_RightTab@0autnc`} isAllWorkPlan={this.props.isAllWorkPlan} workType={this.props.workType}/>
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@qqcttc`} spinning={isSpinning}>
          <div id="gridcontainer" style={{ overflowY: 'visible', visibility: 'visible', display: workPlanShow == 'calender' ? 'block' : 'none', paddingTop: '45px' }}>
          </div>
          <div style={{ display: workPlanShow == 'calender' ? 'none' : 'block', overflowY: 'auto', height: '100%', width: '100%', paddingTop: '45px' }}>
            {/*  表单左侧 */}
            <div className='table-left ' ref='tableLeft' style={{border: '0px solid red',height: this.state.isIE&&timeType==='month' ? "100%" :(timeType==='month' ? "calc(100% - 8px)" : '100%')}}>
                <table className="room-plan-tab-header" style={{width: '100%',height: '45px',lineHeight: '45px',borderSpacing: '0px',borderBottom: '1px solid #E2E2E2',borderRight:'1px solid #E2E2E2'}} >
                  <tbody>
                    {tableHeaders && tableHeaders.length > 0 && (
                      <tr style={{height: '45px'}}>
                        {amAndPm &&<td className="onlyShow" style={{borderRight:'0px'}}><div style={{ width: '104px' }} >{dataRuleStr}</div></td>}
                        {amAndPm &&<td className="onlyShow" ><div style={{ width: '34px' }} ></div></td>}
                        {!amAndPm && <td className="onlyShow" ><div style={{ width: '140px' }} >{dataRuleStr}</div></td>}
                        {/* {!amAndPm &&<td className="onlyShow" ><div style={{ width: '34px' }} ></div></td>} */}
                      </tr>
                    )}
                  </tbody>
                </table>
                {(memberids && memberids.length > 0) && <div className='left-content' id='left-content-tr' ref='leftContent' style={{ overflow: 'hidden',background: this.state.color, height: this.state.isIE&&timeType==='month' ? 'calc(100% - 63px)' : 'calc(100% - 47px)' }}>
                  {leftContent}
                </div>}
            </div>
            {/* 表单右侧 */}
            <div className='table-right' style={{width: timeType==='week' ? (amAndPm? 'calc(100% - 170px)':'calc(100% - 146px)') 
              : tableContent&&tableContent.length>0 ? (amAndPm?'calc(100% - 170px)' :'calc(100% - 150px)') :'calc(100% - 150px)', 
                    height: this.state.isIE&& timeType==='month' ? '100%' : '100%'}}>
              <div className='right-header right-top' ref='hearderTimeItem' style={{ width: this.state.isIE ? (timeType==='week'&&weekScrolllwidth  ? `calc(100% - 17px)` :'calc(100% - 0px)' ):(timeType==='week'&&weekScrolllwidth  ? `calc(100% - 7px)` :'calc(100% - 0px)'),
                    overflow: timeType==='month' && tableContent ? 'hidden' : 'auto',border: '0px solid red' }}>
                <table className="room-plan-tab-header" style={{}}>
                  <tbody>
                    {tableHeaders && tableHeaders.length > 0 && (
                      <tr className='hearderTimeItem' style={{whiteSpace: 'nowrap',height: '45px'}}>
                        {tableHeaders.map((header) => {
                          return (<td style={{border: 0,borderRight: '1px solid #e2e2e2',borderBottom: '1px solid #e2e2e2'}}><div style={thHeaderStyle} ><span>{header}</span></div></td>);
                        })}
                      </tr>
                    )}
                  </tbody>
                </table>
               
              </div>
              {(memberids && memberids.length > 0) && <div className="right-top" id='display-workplanItem-container'
                ref='rightTop'
                style={{ overflow: 'auto', height: 
                  this.state.isIE && timeType==='month' ? (tableContent&&tableContent.length>0 ? 'calc(100% - 45px)' : 'calc(100% - 62px)')
                  : (timeType==='month' && tableContent===false ? 'calc(100% - 53px)' : 'calc(100% - 47px)')}}
                onScroll={this.onscroll}
              >
                <table className="room-plan-tab-header"  id='right_content_display' ref='rightTable' style={{}} >
                  <tbody style={{}}>
                    {tableContent}
                  </tbody>
                </table>
              </div>}
            </div>
          </div>
        </Spin>
      </div>
    )
  }

  soveScrollbarWidth = () => {
    const { status } = this.props.myWorkPlanStore
    let { timeType} = status
    if(this.refs.rightTable && this.refs.rightTop && this.refs.rightTable.offsetHeight > this.refs.rightTop.offsetHeight) {
      return true;
    }
    return false;
  }

  onscroll = (e) => {
    const { status, changetableScrollltop } = this.props.myWorkPlanStore
    let { timeType} = status
    if(timeType == 'month') {
      this.refs.leftContent.scrollTop = e.target.scrollTop;
      if(e.target.scrollLeft + this.refs.rightTop.clientWidth >= this.refs.rightTable.scrollWidth) {
        this.refs.hearderTimeItem.scrollLeft = e.target.scrollLeft;
      }else{
        this.refs.hearderTimeItem.scrollLeft = e.target.scrollLeft;
      }
    }else{
      this.refs.hearderTimeItem.scrollLeft = e.target.scrollLeft;
      this.refs.leftContent.scrollTop = e.target.scrollTop;
    }
  }

  createTdList = (room, blockNum, useMap, dayOfWeek, thStyle) => {
    let HH = '25px';
    const { status } = this.props.myWorkPlanStore
    let { timeType, date, dateMoment, titleFold } = status
    let titleFoldStyle = titleFold === 1 ? {} : {whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',} ;
    let isHeight = titleFold === 1 ? {} : {};
    useMap = toJS(useMap);
    let tdList = [];
    let useArray = useMap[room.id];
    if (timeType == 'week' || timeType == 'month') {
      for (let i = 0; i < blockNum; i++) {
        tdList.push([]);
      }
      useArray && useArray.forEach((obj, index) => {
        let thStyleCopy = { ...thStyle,...isHeight, backgroundColor: obj.color, textAlign: 'left', borderBottom: '1px solid #fff', /*whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',*/color: obj.fontcolor ? obj.fontcolor : '#fff' ,cursor: 'pointer'}
        let tdIdx = ''
        if (timeType == 'month') {
          tdIdx = Number(obj.begindate.split('-')[2] - 1)
        }
        if (timeType == 'week') {
          tdIdx = dayOfWeek.indexOf(`${obj.begindate}`)
        }
        if (tdIdx < 0 || tdIdx >= blockNum) return;
        let workid = []
        workid.push(obj.id);
        tdList[tdIdx].push(<Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@cayk9r@${obj.id}`} title={obj.title.map((tip) => <div>{tip}</div>)} placement="bottomRight" >
          <div onClick={() => { this.view(workid) }} style={thStyleCopy}>
            <div style={{...titleFoldStyle,paddingTop: '5px',paddingBottom: '5px',minHeight:HH,wordBreak: 'break-all',}}>
             {`${obj.showname}`}
            </div>
          </div>
        </Tooltip>)
      });
      for (let i = 0; i < blockNum; i++) {
        thStyle = { ...thStyle, minHeight: HH }
        tdList[i].push(<div className="roomplan-td-modal" style={thStyle}></div>);
      }
      return (tdList.map((e,index) => {
        if(timeType === 'week' && dayOfWeek[index] === moment().format('YYYY-MM-DD')){ // 当天做颜色处理
          return <td style={{backgroundColor: '#ffc'}}>{e}</td>
        }else if(timeType === 'month' && dayOfWeek[index] === moment().format('YYYY-MM-DD')) {
          return <td style={{backgroundColor: '#ffc'}}>{e}</td>
        }else{
          return <td>{e}</td>
        }
      }));
    } else {
      tdList.push([]);
      useArray && useArray.forEach((obj) => {
        let thStyleCopy = { ...thStyle,width:'100%', lineHeight: HH, backgroundColor: obj.color, textAlign: 'left', borderBottom: '1px solid #fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: obj.fontcolor ? obj.fontcolor : '#fff',cursor: 'pointer' }
        let workid = []
        workid.push(obj.id);
        // tdList[0].push(<div style={thStyleCopy}>{`${obj.showname}`}</div>)
        tdList[0].push(<Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@b16uij@${obj.id}`} placement='topLeft' arrowPointAtCenter title={obj.title.map((tip) => <div>{tip}</div>)} placement="bottomRight" >
          <div onClick={() => { this.view(workid) }} style={thStyleCopy}>{`${obj.showname}`}</div>
        </Tooltip>)
      });
      thStyle = { ...thStyle, minHeight: HH }
      tdList[0].push(<div className="roomplan-td-modal" style={thStyle}></div>);
      return <td style={{backgroundColor: dayOfWeek[0] === moment().format('YYYY-MM-DD') ? '#ffc' : ''}}>{tdList[0]}</td>

    }
  }

  getTableHeaderInfo = (timeType, date) => {
    let { status } = this.props.myWorkPlanStore
    let { weekstartday } = toJS(status);
    let blockNum = 0, tableTitle = '', tableHeaders = [];
    let dateCopyMoment = moment(date);
    let weekday = new Array(7)
    weekday[0] = getLabel(16106,'周日')
    weekday[1] = getLabel(16100,'周一')
    weekday[2] = getLabel(16101,'周二')
    weekday[3] = getLabel(16102,'周三')
    weekday[4] = getLabel(16103,'周四')
    weekday[5] = getLabel(16104,'周五')
    weekday[6] = getLabel(16105,'周六')

    if (timeType == 'day') {
      blockNum = 1;
      let dayMoment=dateCopyMoment.day(dateCopyMoment.day());
      tableTitle = dayMoment.format(i18n.moment.dateformat.Md)+" ("+weekday[dayMoment.day()]+")";
      // tableTitle = dateCopyMoment.format(i18n.moment.dateformat.Md+" ("+weekday[dateCopyMoment.day()]+")");//"M月D日（ddd）"
      tableHeaders.push(tableTitle);
    } else if (timeType == 'week') {
      blockNum = 7;
      //tableTitle = dateCopyMoment.format("YYYY年ww周");
      for (var i = 0; i < blockNum; i++) {
        if (weekstartday == 0) {
          let dayMoment=dateCopyMoment.day(i);
          tableHeaders.push(dayMoment.format(i18n.moment.dateformat.Md)+" ("+weekday[dayMoment.day()]+")");
        } else if (weekstartday == 1 && dateCopyMoment.day() > 0) {
          let dayMoment=dateCopyMoment.day(i+1);
          tableHeaders.push(dayMoment.format(i18n.moment.dateformat.Md)+" ("+weekday[dayMoment.day()]+")");
        } else if (weekstartday == 1 && dateCopyMoment.day() == 0) {
          let dayMoment=dateCopyMoment.day(i-7+1);
          tableHeaders.push(dayMoment.format(i18n.moment.dateformat.Md)+" ("+weekday[dayMoment.day()]+")");
        }
      }
    } else {
      blockNum = dateCopyMoment.daysInMonth();
      //tableTitle = dateCopyMoment.format("YYYY年MM月") + `（${blockNum}天）`;
      let month = dateCopyMoment.month();
      let year = dateCopyMoment.year();
      let monthStr = (month+1) > 9 ? (month+1) : '0'+(month+1);
      let firstDay=moment(year+"-"+(monthStr)+"-01");
      let md=firstDay.format(i18n.moment.dateformat.Md);
      let day=firstDay.day();
      tableHeaders.push(`${md} (${weekday[day]})`);
      for (var i = 1; i < blockNum; i++) {
        firstDay=firstDay.add(1,'days');
        md=firstDay.format(i18n.moment.dateformat.Md);
        day=firstDay.day();
        tableHeaders.push(`${md} (${weekday[day]})`);
      }
    }
    return { blockNum: blockNum, tableTitle: tableTitle, tableHeaders: tableHeaders };
  }
  changeInit = (bool) => {
    let { status, updateCalender } = this.props.myWorkPlanStore;
    status = toJS(status);
    let { update, isInit, workPlanShow } = status;
    let { changeInit } = this.props.myWorkPlanStore;
    changeInit(bool);
  }
  doRefreshCalender = (data, selected, selectedUser, canSave = false, date, canLoad = false) => {//第一个参数data为（data数据），selected为日程类型，初始化传空，之后传该值,canSave是否可以保存
    let {  query = false} = this.props;
    let { status, getRightMenu, onRightMenuClick, changeTimeType, DATA_FEED_URL, doUpdateCalender, updateCalender, changeSpinning,dialogHeight } = this.props.myWorkPlanStore
    status = toJS(status);
    let { loading, timeType, userList, defBgTime, defEdTime, defBgTimeStr, defEdTimestr, isInit, weekstartday, zone_offset } = status;
    selected = selected == '-9900' ? '' : selected;
    timeType = timeType == '' ? 'week' : timeType;
    let { isAllWorkPlan = false } = this.props;
    let isShareCopy = isAllWorkPlan ? 2 : 1;
    //获取客户端时区
    let millTime = new Date(date).getTime();
    if(typeof(date)==='string'){
      const clientTimeZone = new Date().getTimezoneOffset()/60;
      if(zone_offset !== (-clientTimeZone)){
        millTime = millTime + (clientTimeZone+zone_offset)*60*60*1000;
      }
    }
    let op = {
      view: timeType,//指定显示的视图（周，月，日）
      theme: 1,//指定默认模板，比如拖拽新建日程时日程的颜色
      showday: new Date(millTime),//指定显示的日期，在视图中显示的日， 周，月为当前指定日期所在的日，周，月。
      DeleteCmdhandler: () => { },//删除日程的回调函数
      EditCmdhandler: (e) => { this.edit(e) },//编辑日程的回调函数
      ViewCmdhandler: (e) => { this.view(e) },//查看日程的回调函数
      autoload: false,
      canLoad: canLoad,    
      defBgTime: defBgTime,
      defEdTime: defEdTime,
      defBgTimeStr: defBgTimeStr,
      defEdTimestr: defEdTimestr,
      selectedUser: selectedUser,//指定当前选定的人员
      isShare: isShareCopy,//（isShare：1 显示“所有日程”，其他：显示“我的日程”
      workPlanType: selected,
      quickAddHandler: true,
      doGetData: () => { this.getData() },//E9获取数据的接口
      newData: data,//E9data数据
      canSave: canSave,//E9是否将数据渲染到页面
      doDrog: (params) => { this.drog(params) },//拖动实现编辑
      weekstartday: weekstartday,//日历从周几开始，0为周日，1为周一
    };
    // let _MH = document.documentElement.clientHeight;
    let _MH = jQuery("#workPlan-myWorkPlan-id").height();
    let topH = 0; // weatop
    let tabH = 45;  // 日程类型，时间模式，datepicker
    let timelabelH = 45; // 周一 ~ 周日
    if (jQuery(".wea-new-top-wapper")) {
      topH = jQuery(".wea-new-top-wapper").height();
    } 
    let _dvH = _MH - topH - tabH + 9;
    if(window.location.href.indexOf("/spa/workplan/static/index")>-1||window.location.href.indexOf("/#/")>-1){
      // _dvH = _MH -144 + 8 + 30 + 8;
    }
    op.height = _dvH;
    if(query && query.hrmWorkplanHeight){//人力卡片里面调用日程的时候会传高度
      op.height = query.hrmWorkplanHeight;
    }
    if(dialogHeight>0){
      op.height =dialogHeight-144 + 8;
    }
    jQuery("#gridcontainer").BcalSetOp(op);
    doUpdateCalender(false);//关闭手动刷新
    canLoad && this.getData()
  }
  view = (e) => {
    this.props.myWorkPlanStore.open('preview', e[0], '')
  }
  edit = (e) => {
    if (this.props.cancreate === 'false') return; // 通过url判断是否允许新建

    this.props.myWorkPlanStore.open('create', '', e)
  }
  query=(name) => {
    if(window.location.hash.indexOf('?')>-1){
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var params = window.location.hash.split('?')[1];
      var r = params.match(reg);
      if (r != null ) return unescape(r[2]);
      return null;
    }
   
  }
  getData = (bool = true) => {
    const { status, getRightMenu, onRightMenuClick, changeTimeType, DATA_FEED_URL, changeSpinning } = this.props.myWorkPlanStore
    let { loading, timeType, userList, selected, selectedUser, date, defBgTime, defEdTime, defBgTimeStr, defEdTimestr, isShare, isInit, calendarInit } = status;
    let a = this.changeDateFormat(date)
    changeSpinning(true);
    let newSelected = selected == '-9900' ? '' : selected;

    let viewType = timeType == 'day' ? 1 : timeType == 'week' ? 2 : 3
    let isOtherPage = this.query("isOtherPage")
    let worktype=this.query("workType")

    // if (typeof workType == 'undefined') {
    //   console.log('555', this.props.workType)
      // if(isOtherPage){
      //   if (worktype && typeof worktype === 'string') { // 通过url获取日程类型
      //     let arrs = worktype;
      //     if (arrs == -1) {
      //       newSelected = '';
      //     } else {
      //       newSelected = arrs;
      //     }
      //   }
      // }else {
        if (this.props.workType && typeof this.props.workType === 'string') { // 通过url获取日程类型
          let arrs = this.props.workType;
          if (arrs == -1) {
            newSelected = '';
          } else {
            newSelected = arrs;
          }
        }
      //   }
      // }
      
    // } else {
    //     if((workType==-1||workType==0)){
    //       let arrs = workType
    //       if (arrs == -1) {
    //         newSelected = '';
    //       } else {
    //         newSelected = arrs;
    //       }
    //     }

    // }
    if(isOtherPage){
      if (worktype && typeof worktype === 'string') { // 通过url获取日程类型
            let arrs = worktype;
            if (arrs == -1) {
              newSelected = '';
            } else {
              newSelected = arrs;
            }
          }
    }
    if(!isOtherPage&&thisSign!=nextSign){
      newSelected = selected == '-9900' ? '' : selected;
    }
    let params = {
      selectUser: selectedUser,
      selectDate: this.changeDateFormat(date),
      workPlanType: newSelected,
      viewType: viewType,
    }

    bool && isInit && $("#gridcontainer").BcalSetDate(calendarInit);
    bool && !isShare && myWorkPlanApi.MyCalendar(params).then((result) => {
      result.events.map(c => {
        c[1] = c[1].replace(/(<br>|<\/br>)/g,' ');
        c[1] = c[1].replace(/>/g,' ');
      });
      let { status } = this.props.myWorkPlanStore;
      status = toJS(status)
      let { isShare, selectedUser, date, selected, timeType } = status
      let newSelected = selected == '-9900' ? '' : selected;
      let viewType = timeType == 'day' ? 1 : timeType == 'week' ? 2 : 3
      changeSpinning(false);//加载完毕

      $("#gridcontainer").BcalSetDate(result); // 先将前面的判断去除，暂不知有啥作用2019-07-29
      // !isShare && params.selectUser == selectedUser && params.selectDate == this.changeDateFormat(date) && params.workPlanType == newSelected && params.viewType == viewType && $("#gridcontainer").BcalSetDate(result);
    });
    bool && isShare && myWorkPlanApi.AllCalendar(params).then((result) => {
      result.events.map(c => {
        c[1] = c[1].replace(/(<br>|<\/br>)/g,' ');
        c[1] = c[1].replace(/>/g,' ');
      });
      let { status } = this.props.myWorkPlanStore;
      status = toJS(status)
      let { isShare, selectedUser, date, selected, timeType } = status
      // let newSelected = selected == '-9900' ? '' : selected;
      let viewType = timeType == 'day' ? 1 : timeType == 'week' ? 2 : 3
      changeSpinning(false);//加载完毕
      isShare && params.selectUser == selectedUser && params.selectDate == this.changeDateFormat(date) && params.workPlanType == newSelected && params.viewType == viewType && $("#gridcontainer").BcalSetDate(result);
    });

  }
  drog = (params) => {
    const { status } = this.props.myWorkPlanStore
    let { selectedUser } = status;
    params = { ...params, isShare: '', selectedUser: selectedUser }
    myWorkPlanApi.editCalendarItemQuick(params).then((result) => {
    });
  }
  changeDateFormat = data => {
    if (typeof (data) === 'string' && data != '') {
      return data
    }
    //日期格式转为yyyy-MM-dd
    let now = data || new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString();
    let day = (now.getDate()).toString();
    if (month.length == 1) {
      month = "0" + month;
    }
    if (day.length == 1) {
      day = "0" + day;
    }
    let dateString = year + "-" + month + "-" + day;
    return dateString;
  }

}
let createTitle = function (titleList) {
  if (Array.isArray(titleList) && titleList.length > 0) {
    return (
      <div className="wea-roomplan-titletip">
        {titleList.map((meet, idx) => {
          return (
            <div>
              {meet.map((tip) => <div>{tip}</div>)}
              {idx + 1 < titleList.length && <div className="line" />}
            </div>
          );
        })}
      </div>
    );
  }
  return undefined;
}

export default RightContainer
